import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import jwt from 'jsonwebtoken';
import { PUBLIC_KEY } from '../app/app.config';
import { getUser, getPending, getMenu, createAuthority, updateAuthority } from './mainPage.service';


/**
 * 获取首页内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let status = 0;
  try {
    // 获取用户统计
    const data = await getUser();

    // 待审核统计
    // const pending = await getPending(status);
    
    let res = {
      data
      // pending
    }
    response.send(res)
  } catch (error) {
    next(error)
  }
}

/**
 * 获取菜单
 */
export const menu = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  try {
    let authentication = request.headers.authentication;
    let decoded = jwt.verify(`${authentication}`, PUBLIC_KEY, {
      algorithms: ['RS256']
    });
    let _decoded = decoded as any
    let admin_id = _decoded.id;
    
    // 获取菜单
    const data = await getMenu(admin_id);
    
    response.send(data)
  } catch (error) {
    next(error)
  }
}

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let menuModel = request.body;

  let user = request.user;
  if (user.type != 1) {
    menuModel.user_id = user.id
  }

  // 创建内容
  try {
    const data = await createAuthority(menuModel);
    response.send(data);
  } catch (error) {
    console.log(error);
  }
    
}

/**
 * 更新内容
 */
export const update = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { postId } = request.params;

  // 更新内容
  const post = _.pick(request.body, [
    'admin_id',
    'menu_id'
  ]);

  // 更新内容
  try {
    const data = await updateAuthority(post, parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}
